package cn.smile.util;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

/**
 * 项目通用工具类
 */
@Slf4j
public class StringUtil {

    /**
     * 返回指定格式的日期字符串
     */
    public static String getFormatterDate(Date date, String formatter) {
        SimpleDateFormat sdf = new SimpleDateFormat(formatter);
        return sdf.format(date);
    }

    /**
     * 判断请求是否是ajax
     */
    public static boolean isAjax(HttpServletRequest request) {
        String header = request.getHeader("X-Requested-With");
        return "XMLHttpRequest".equals(header);
    }

    /**
     * 从流读取字符串
     */
    public static String getStringFromInputStream(InputStream inputStream) {
        StringBuilder string = new StringBuilder();
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "GB2312"));
            String buf;
            try {
                while ((buf = bufferedReader.readLine()) != null) {
                    string.append(buf);
                }
            } catch (Exception e) {
                log.error("处理异常, e: ", e);
            } finally {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    log.error("处理异常, e: ", e);
                }
            }
        } catch (Exception e) {
            log.error("处理异常, e: ", e);
        }
        return string.toString();
    }
}
